package cn.lyz.authority.filter;

import cn.lyz.authority.common.utils.JwtTokenUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j2;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Log4j2
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private final JwtTokenUtil jwtTokenUtil;
    private final UserDetailsService userDetailsService;

    public JwtAuthenticationTokenFilter(JwtTokenUtil jwtTokenUtil, UserDetailsService userDetailsService) {
        this.jwtTokenUtil = jwtTokenUtil;
        this.userDetailsService = userDetailsService;
    }
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取Authorization header中的JWT令牌
        String authHeader = request.getHeader("Authorization");
        if(StringUtils.isNotBlank(authHeader) && authHeader.startsWith("Bearer ") && authHeader.length() > 7) {
            String token = authHeader.split(" ")[1]; // 去除"Bearer "前缀
            // 验证JWT令牌
            if(!jwtTokenUtil.validateToken(token)) {
                throw new InsufficientAuthenticationException("令牌无效");
            }
            // 解析JWT令牌，获取用户信息
            Claims claims = jwtTokenUtil.getClaimsFromToken(token);
            String username = claims.getSubject();

            // 加载用户详细信息
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);

            // 创建认证令牌
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

            // 将认证令牌设置到SecurityContext中
            SecurityContextHolder.getContext().setAuthentication(authentication);
            // 将请求和响应传递给过滤器链中的下一个过滤器或目标资源
            filterChain.doFilter(request, response);
        }

        // 将请求和响应传递给过滤器链中的下一个过滤器或目标资源
        filterChain.doFilter(request, response);
    }
}